import os
from os import path
from log import logger

cwd = os.getcwd()

# toolchains options
ARCH='arm'
CPU='cortex-m4'
CROSS_TOOL='gcc'
BUILD = 'debug'
PROJECT = 'v4'
EXEC_PATH = cwd

ROOT_PATH = cwd
BUILD_PATH = path.join(cwd,'build')

LINKSCRIPT = 'STM32F407VGTx_FLASH.ld'
if  CROSS_TOOL == 'gcc':
    PLATFORM    = 'posix'
    tmp = os.getenv('ARM_GCC_ROOT')
    if tmp != None:
        EXEC_PATH   = path.join(tmp,'bin')
    else:
        pass

if PLATFORM == 'posix':
    # toolchains
    PREFIX = 'arm-none-eabi-'
    CC = PREFIX + 'gcc'
    AS = PREFIX + 'gcc'
    AR = PREFIX + 'ar'
    CXX = PREFIX + 'g++'
    LINK = PREFIX + 'gcc'
    TARGET_EXT = '.elf'
    SIZE = PREFIX + 'size'
    OBJDUMP = PREFIX + 'objdump'
    OBJCPY = PREFIX + 'objcopy'

    DEVICE = ' -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard -ffunction-sections -fdata-sections'
    ASDEVICE = ' -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard'
    CFLAGS = DEVICE + ' -Dgcc'
    # AFLAGS = ' -c' + ASDEVICE + ' -mimplicit-it=thumb '
    AFLAGS = ' -c' + DEVICE + ' -x assembler-with-cpp -Wa,-mimplicit-it=thumb '
    LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=' + path.join(BUILD_PATH,PROJECT + '.map') + ',-cref,-u,Reset_Handler -T ' + LINKSCRIPT

    CPATH = ''
    LPATH = ''

    if BUILD == 'debug':
        CFLAGS += ' -O0 -gdwarf-2 -g'
        AFLAGS += ' -gdwarf-2'
    else:
        CFLAGS += ' -O2'

    CXXFLAGS = CFLAGS 

    TARGET = PROJECT + TARGET_EXT

    POST_ACTION = OBJCPY + ' -O binary $TARGET ' +path.join(BUILD_PATH,PROJECT + '.bin') +'\n' + SIZE + ' $TARGET \n'

# usr def

def get_file(dir,macth,recusive=False):
    files=[]
    for d in os.listdir(dir):
        fd = path.join(dir,d)

        if path.isdir(fd) and recusive:
            files += get_file(fd,macth,recusive)
        elif path.isfile(fd):
            x,y = path.splitext(fd)
            if y in macth:
                files += [fd]
    return files

getTargetName = lambda target_dir,filename : path.join(target_dir,path.split(os.getcwd())[1],path.splitext(filename)[0]+'.o')

